package com.test.javafaq_faq.controller;



import com.test.javafaq_commons.entity.Comment;
import com.test.javafaq_commons.vo.R;
import com.test.javafaq_faq.service.ICommentService;
import com.test.javafaq_faq.vo.CommentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author test.com
 * @since 2025-04-11
 */
@RestController
@RequestMapping("/v1/comments")
@Slf4j
public class CommentController {

    @Autowired
    ICommentService commentService;

    @PostMapping("/{id}/update")
    public R updateComment(@PathVariable Integer id, @Validated CommentVo commentVo,
                           BindingResult res, @AuthenticationPrincipal UserDetails user){
        if(res.hasErrors()){
            String msg = res.getFieldError().getDefaultMessage();
            return R.unproecsableEntity(msg);
        }
        log.debug("评论id:{}",id);
        log.debug("开始修改评论:{}",commentVo);

        Comment comment = commentService.upadateComment(id, commentVo, user.getUsername());
        return R.ok(comment);
    }

    //删除评论的方法
    @GetMapping("/{id}/delete")
    public R removeComment(@PathVariable Integer id,@AuthenticationPrincipal UserDetails user){
        log.debug("开始删除评论:{}",id);
        boolean isDelete = commentService.removeComment(id,user.getUsername());

        if(isDelete)
            return R.gone("删除成功");
        else
            return R.notFound("没有找到对应评论");
    }

    @PostMapping
    public R<Comment> postComment(@Validated CommentVo commentVo, BindingResult res, @AuthenticationPrincipal UserDetails user){
        if(res.hasErrors()){
            String msg = res.getFieldError().getDefaultMessage();
            return R.unproecsableEntity(msg);
        }
        log.debug("开始新增评论：{}",commentVo);
        Comment comment = commentService.saveComment(commentVo, user.getUsername());

        return R.create(comment);
    }


}
